import type { PickerColumn } from 'antd-mobile/es/components/picker-view'
import { Dialog, Picker, Toast } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { RightOutline } from 'antd-mobile-icons'
import { useLocalObservable, useObserver } from 'mobx-react'
import { approveClass, fetchTrainPlan } from '../api'
import { history } from 'umi'
import { asserts, pxToRpx } from '@/utils/share'
import UploadImage from '@/components/Global/UploadImage'
import Btn from '@/components/Global/Btn'
import styles from './index.module.less'

const ClassAuditApprove = () => {
    const queryParams = history.location.query as { id: string }

    const [value, setValue] = useState<(string | null)[]>(['M'])

    const store = useLocalObservable(() => ({
        formData: {
            /** 计划班级id */
            planId: undefined as string | undefined,
            /** 盖章件路径 */
            image: undefined as string | undefined,
            /** 盖章件名称 */
            imageName: undefined as string | undefined,
        },

        /** 培训计划列表 */
        columns: [] as PickerColumn[],

        async fetchTrainPlanToStore() {
            const data = await fetchTrainPlan(Number(queryParams.id))
            if (!data) return

            if (asserts.isArray(data)) {
                store.columns = [data.map((item, i) => ({ label: item, value: String(i) }))]
            } else {
                store.columns = [
                    Object.entries(data).map(([k, v]) => ({
                        label: v,
                        value: String(k),
                    })),
                ]
            }
        },
    }))

    useEffect(() => {
        const fetch = async () => {
            const tostShow = Toast.show({
                icon: 'loading',
                content: '加载中...',
                duration: 0,
            })
            await store.fetchTrainPlanToStore()
            tostShow.close()
        }

        fetch()
    }, [store])

    /** 通过 */
    const onApprove = async () => {
        const { planId, image, imageName } = store.formData

        if ([planId, image, imageName].some(v => v === undefined)) {
            Toast.show({ icon: 'fail', content: '请填写必填项！' })
            return false
        }

        try {
            await approveClass(Number(queryParams.id), {
                plan_group_id: planId!,
                check_image: image!,
                check_image_name: imageName!,
            })

            Dialog.alert({
                title: '开班审核确认',
                content: (
                    <div style={{ textAlign: 'center', color: '#666' }}>
                        已明确当地疫情防控工作要求，并同意开展此次培训
                    </div>
                ),
                confirmText: '已知晓 ',
                onConfirm: () => {
                    history.push('/train?tab=classAudit')
                },
            })
        } catch (error) {}
    }

    return useObserver(() => {
        return (
            <>
                <div className={styles.page}>
                    <Picker
                        columns={store.columns}
                        value={value}
                        onConfirm={setValue}
                        onSelect={([planId]) => {
                            if (planId) store.formData.planId = planId
                        }}
                    >
                        {([items], { open }) => {
                            return (
                                <div className={styles.picker} onClick={open}>
                                    <div>
                                        <label className={styles.label}>关联计划开班</label>
                                        <span>{items ? items.label : '请选择'}</span>
                                    </div>
                                    <RightOutline color="#ccc" />
                                </div>
                            )
                        }}
                    </Picker>

                    <div className={styles.uploadImg}>
                        <div className={styles.label}>上传盖章件</div>
                        <UploadImage
                            accept="jpg,png"
                            maxCount={1}
                            onChange={([file]) => {
                                store.formData.imageName = file?.extra?.name
                                store.formData.image = file?.url
                            }}
                        />
                        <div style={{ marginTop: pxToRpx(8), color: '#999' }}>
                            只允许上传jpg，png格式
                        </div>
                    </div>
                </div>

                <div className={styles.operation}>
                    <Btn block color="primary" task={onApprove}>
                        提交审核
                    </Btn>
                </div>
            </>
        )
    })
}

export default ClassAuditApprove
